import { AjaxService, Req, Res } from "./ajax.service"
import { Injectable } from '@angular/core'

import { Daily } from "./daily"
import { Task } from './task'

@Injectable()
export class DailyService {
  private bh = AjaxService.APIROOT + '/dailys';

  save(daily): Promise<Res> {
      var argv = { daily: daily, token: localStorage.getItem("token") }
   if(daily.id){

      return AjaxService.request(new Req(`${this.bh}/${daily.id}.json`, "PUT", argv))
    }

    else {
       return AjaxService.request(new Req(`${this.bh}.json`, "POST", argv))
    }
   
  }


    get(id: string): Promise<Daily> {
    var daily: Daily
    return new Promise<Daily>(resolve => {
      AjaxService.request(new Req(`${this.bh}/${id}.json`, "GET"))
          .then(res => {
            if (!res.error)
              daily = res.data
            resolve()
          }).catch((err: any) => { console.log("get task error", err) })
    }).then(() => daily)
  }

  


    list(args: Object): Promise<Array<Task>> {
    var argv = args
    if (localStorage.getItem("token"))
      argv["token"] = localStorage.getItem("token")
    var tasks: Array<Task> = [ ]
    return new Promise<Array<Task>>(resolve => {
        AjaxService.request(new Req(`${this.bh}.json`, "GET", argv))
          .then(res => {
            if (!res.error)
              tasks = res.data
            resolve()
          }).catch((err: any) => { console.log("get tasks error", err) })
      }).then(() => tasks)
  }
}